/**
 * Created by Saxon Cheng on 2017/3/16.
 */
import RnPay from '../payment/PaySDK';
import {put, take, call, fork,select} from 'redux-saga/effects';
import * as ActionType from "../constants/ActionType"
import * as PayAction from "../actions/PayAction";
import * as Request from "../utils/httpUtil";
import * as API from '../constants/ApiService';
import * as PayUtil from '../constants/PayConfig';

function* createProduct(workId,workType,userId,payType) {
    try {
        let result = yield call(Request.postRequest,API.CREATE_PAYORDER(payType),{workId,workType,userId})
        if(result.success){
            let orderInfo = result.result.orderInfo;
            let params ;
            if(payType===PayUtil.ALIPAY){
                params = {
                    orderInfo:orderInfo,
                };
            }else {
                params = {
                    appid:PayUtil.WX_APPID,
                    money:'',
                    desc:'',
                    partnerid:'',
                    parpayid:'',
                    packageValue:'',
                    noncestr:'',
                    timestamp:'',
                    sign:''
                };
            }
            yield put(PayAction.fetchProductDone(params))
        }else {
            yield put(PayAction.fetchProductERROR(result.errorMsg))
        }
    } catch (error) {
        yield put(PayAction.fetchProductERROR(error))
    }
}

function* pay(params,payType) {
    if(payType==PayUtil.ALIPAY){
        RnPay.onAliPay(params.orderInfo)
            .then((res)=>{
                console.log(res);
            })
            .catch((error)=>{
                if(error.code==='4000'){
                    console.log(error.message);
                }else if(error.code==='6001'){
                    console.log("取消支付");
                }else if(error.code==='6002'){
                    console.log("网络错误");
                }
            })
    }else {
        RnPay.onWxPay(params)
    }
}

export function* watchCreateProduct() {
    while (true) {
        const {
            workId,
            workType,
            userId,
            payType
        } = yield take(ActionType.FETCH_PRODUCTID_START);
        yield fork(createProduct,workId,workType,userId,payType);
    }
}

export function* watchProductDone() {
    while (true) {
        yield take(ActionType.FETCH_PRODUCTID_DONE);
        const newState = yield select();
        let state = newState.payReducer;
        if(state.paySuccess){
            yield fork(pay,state.params,state.payType);
        }
    }
}
